package com.luo.backend.controller;

import com.luo.backend.common.ApiResponse;
import com.luo.backend.dto.MerchantOrderStatsResponse;
import com.luo.backend.dto.OrderResponse;
import com.luo.backend.dto.RejectOrderRequest;
import com.luo.backend.entity.User;
import com.luo.backend.repository.UserRepository;
import com.luo.backend.service.MerchantOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 商家订单管理接口
 */
@RestController
@RequestMapping("/api/v1/merchant/orders")
public class MerchantOrderController {
    
    private static final Logger logger = LoggerFactory.getLogger(MerchantOrderController.class);
    
    @Autowired
    private MerchantOrderService merchantOrderService;
    
    @Autowired
    private UserRepository userRepository;
    
    /**
     * 获取当前登录用户
     */
    private User getCurrentUser(Authentication authentication) {
        Long userId = (Long) authentication.getPrincipal();
        return userRepository.findById(userId)
            .orElseThrow(() -> new RuntimeException("用户不存在"));
    }
    
    /**
     * 获取商家订单统计
     * GET /api/v1/merchant/orders/stats
     */
    @GetMapping("/stats")
    public ApiResponse<MerchantOrderStatsResponse> getOrderStats(Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            MerchantOrderStatsResponse stats = merchantOrderService.getOrderStats(user.getMerchantId());
            return ApiResponse.success(stats);
            
        } catch (Exception e) {
            logger.error("获取订单统计失败", e);
            return ApiResponse.error("获取订单统计失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取商家订单列表
     * GET /api/v1/merchant/orders?status=pending&page=1&pageSize=10
     */
    @GetMapping
    public ApiResponse<List<OrderResponse>> getOrders(
            @RequestParam(required = false) String status,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            List<OrderResponse> orders = merchantOrderService.getOrders(
                user.getMerchantId(), status, page, pageSize);
            
            return ApiResponse.success(orders);
            
        } catch (Exception e) {
            logger.error("获取订单列表失败", e);
            return ApiResponse.error("获取订单列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取订单详情
     * GET /api/v1/merchant/orders/{orderId}
     */
    @GetMapping("/{orderId}")
    public ApiResponse<OrderResponse> getOrderDetail(
            @PathVariable Long orderId,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            OrderResponse order = merchantOrderService.getOrderDetail(user.getMerchantId(), orderId);
            return ApiResponse.success(order);
            
        } catch (Exception e) {
            logger.error("获取订单详情失败", e);
            return ApiResponse.error("获取订单详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 接单
     * POST /api/v1/merchant/orders/{orderId}/accept
     */
    @PostMapping("/{orderId}/accept")
    public ApiResponse<String> acceptOrder(
            @PathVariable Long orderId,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            merchantOrderService.acceptOrder(user.getMerchantId(), orderId);
            return ApiResponse.success("接单成功");
            
        } catch (Exception e) {
            logger.error("接单失败", e);
            return ApiResponse.error("接单失败：" + e.getMessage());
        }
    }
    
    /**
     * 拒单
     * POST /api/v1/merchant/orders/{orderId}/reject
     */
    @PostMapping("/{orderId}/reject")
    public ApiResponse<String> rejectOrder(
            @PathVariable Long orderId,
            @RequestBody RejectOrderRequest request,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            merchantOrderService.rejectOrder(user.getMerchantId(), orderId, request.getReason());
            return ApiResponse.success("拒单成功");
            
        } catch (Exception e) {
            logger.error("拒单失败", e);
            return ApiResponse.error("拒单失败：" + e.getMessage());
        }
    }
    
    /**
     * 开始备货
     * POST /api/v1/merchant/orders/{orderId}/prepare
     */
    @PostMapping("/{orderId}/prepare")
    public ApiResponse<String> startPreparing(
            @PathVariable Long orderId,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            merchantOrderService.startPreparing(user.getMerchantId(), orderId);
            return ApiResponse.success("开始备货");
            
        } catch (Exception e) {
            logger.error("开始备货失败", e);
            return ApiResponse.error("开始备货失败：" + e.getMessage());
        }
    }
    
    /**
     * 开始配送
     * POST /api/v1/merchant/orders/{orderId}/ship
     */
    @PostMapping("/{orderId}/ship")
    public ApiResponse<String> startShipping(
            @PathVariable Long orderId,
            Authentication authentication) {
        try {
            User user = getCurrentUser(authentication);
            
            // 验证是否为商家
            if (!"merchant".equals(user.getRole())) {
                return ApiResponse.error("无权访问");
            }
            
            if (user.getMerchantId() == null) {
                return ApiResponse.error("商家信息不完整");
            }
            
            merchantOrderService.startShipping(user.getMerchantId(), orderId);
            return ApiResponse.success("开始配送");
            
        } catch (Exception e) {
            logger.error("开始配送失败", e);
            return ApiResponse.error("开始配送失败：" + e.getMessage());
        }
    }
}

